package backingBean;

import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import model.Category;
import abstractFactory.Factory;
import dao.Category.CategoryDAO;

public class BeanCategory {
	private Category category = new Category();

	public BeanCategory(){}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public Category editCategory(){
		return category;
	}

	public void register(){
		CategoryDAO categoryDao = Factory.getInstance("JPA").createCategoryDAO();
		if(categoryDao.save(category)){
			FacesMessage msg = new FacesMessage("Cadastrado com Sucesso.");
			FacesContext fc = FacesContext.getCurrentInstance();
			fc.addMessage("gravar", msg);
		}	
		else{
			FacesMessage msg = new FacesMessage("Tente outra vez.");
			FacesContext fc = FacesContext.getCurrentInstance();
			fc.addMessage("gravar", msg);
		}
		category = new Category();
	}

	public List<Category> getCategories(){
		CategoryDAO categoryDao = Factory.getInstance("JPA").createCategoryDAO();
		return categoryDao.getAllCategories();
	}

	public SelectItem[] getItemsCategories(){
		SelectItem categories[] = new SelectItem[getCategories().size()];
		for(int i=0; i<getCategories().size();i++ ){
			categories[i] = new SelectItem(getCategories().get(i),getCategories().get(i).getName());
		}
		return categories;
	}

	public void delete(){
		CategoryDAO categoryDao = Factory.getInstance("JPA").createCategoryDAO();
		category.setActive(0);
		categoryDao.update(category);
		category = new Category();
	}
}